import { useAppStore } from '@/stores/app'
import { showToast } from 'vant'

const initPostMessage = () => {
  console.log('iframe init')
  window.addEventListener('message', receiveMessage)
}

const receiveMessage = (event) => {
  const { data } = event

  try {
    const appStore = useAppStore()

    const msgData = JSON.parse(data)

    const { type } = msgData

    if (type === 'chat') {
      appStore.setIsProBet(false)
      showToast('您已进入聊天版！')
    } else if (type === 'major') {
      appStore.setIsProBet(true)
      showToast('您已进入专业投注版！')
    }
  } catch {
    /* empty */
  }
}
export default initPostMessage

export const changeHallModel = () => {
  if (!top?.window) return
  const appStore = useAppStore()
  appStore.setIsProBet(!appStore.isProBet)
  const type = appStore.isProBet ? 'major' : 'chat'
  const message = JSON.stringify({ type })
  top.window.postMessage(message, '*')
  if (type === 'major') showToast('您已进入专业投注版！')
}
